package mblog.base.vcode;

/**
 * Project  : mblog
 * Author   : Wu Tian Qiang
 * Date     : 2016/6/5
 */

import mblog.base.utils.HttpUtils;
import mblog.base.utils.MD5Utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码识别平台
 */
public class RecognizeCode {


    /**
     * 查询题分
     *
     * @param username 用户名
     * @param password 密码
     * @return response
     * @throws java.io.IOException
     */
    public static String getScore(String username, String password) {
//        String param = String.format("user=%s&pass=%s", username, password);
        Map<String, String> param = new HashMap<>();
        param.put("user", username);
        param.put("pass", password);
        String result;
        try {
            result = HttpUtils.post("http://code.chaojiying.net/Upload/GetScore.php", param);
        } catch (IOException e) {
            result = "未知问题";
        }
        return result;
    }

    /**
     * 注册账号
     *
     * @param username 用户名
     * @param password 密码
     * @return response
     * @throws java.io.IOException
     */
    public static String userReg(String username, String password) {
//        String param = String.format("user=%s&pass=%s", username, password);
        Map<String, String> param = new HashMap<>();
        param.put("user", username);
        param.put("pass", password);
        String result;
        try {
            result = HttpUtils.post("http://code.chaojiying.net/Upload/UserReg.php", param);
        } catch (IOException e) {
            result = "未知问题";
        }
        return result;
    }

    /**
     * 账号充值
     *
     * @param username 用户名
     * @param card     卡号
     * @return response
     * @throws java.io.IOException
     */
    public static String UserPay(String username, String card) {

//        String param = String.format("user=%s&card=%s", username, card);
        Map<String, String> param = new HashMap<>();
        param.put("user", username);
        param.put("card", card);
        String result;
        try {
            result = HttpUtils.post("http://code.chaojiying.net/Upload/UserPay.php", param);
        } catch (IOException e) {
            result = "未知问题";
        }
        return result;
    }

    /**
     * 报错返分
     *
     * @param username 用户名
     * @param password 用户密码
     * @param softid   软件ID
     * @param id       图片ID
     * @return response
     * @throws java.io.IOException
     */
    public static String reportError(String username, String password, String softid, String id) {

//        String param = String.format("user=%s&pass=%s&softid=%s&id=%s", username, password, softid, id);
        Map<String, String> param = new HashMap<>();
        param.put("user", username);
        param.put("pass", password);
        param.put("softid", softid);
        param.put("id", id);
        String result;
        try {
            result = HttpUtils.post("http://code.chaojiying.net/Upload/ReportError.php", param);
        } catch (IOException e) {
            result = "未知问题";
        }

        return result;
    }


    /**
     * 核心上传函数
     *
     * @param url   请求URL
     * @param param 请求参数，如：username=test&password=1
     * @param data  图片二进制流
     * @return response
     * @throws java.io.IOException
     */
    public static String httpPostImage(String url, String param, byte[] data) throws IOException {
        long time = (new Date()).getTime();
        URL u = null;
        HttpURLConnection con = null;
        String boundary = "----------" + MD5Utils.generate(String.valueOf(time));
        String boundarybytesString = "\r\n--" + boundary + "\r\n";
        OutputStream out = null;

        u = new URL(url);

        con = (HttpURLConnection) u.openConnection();
        con.setRequestMethod("POST");
        //con.setReadTimeout(60000);
        con.setConnectTimeout(60000);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(true);
        con.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);

        out = con.getOutputStream();

        for (String paramValue : param.split("[&]")) {
            out.write(boundarybytesString.getBytes("UTF-8"));
            String paramString = "Content-Disposition: form-data; name=\""
                    + paramValue.split("[=]")[0] + "\"\r\n\r\n" + paramValue.split("[=]")[1];
            out.write(paramString.getBytes("UTF-8"));
        }
        out.write(boundarybytesString.getBytes("UTF-8"));

        String paramString = "Content-Disposition: form-data; name=\"userfile\"; filename=\""
                + "chaojiying_java.gif" + "\"\r\nContent-Type: application/octet-stream\r\n\r\n";
        out.write(paramString.getBytes("UTF-8"));

        out.write(data);

        String tailer = "\r\n--" + boundary + "--\r\n";
        out.write(tailer.getBytes("UTF-8"));

        out.flush();
        out.close();

        StringBuffer buffer = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(con
                .getInputStream(), "UTF-8"));
        String temp;
        while ((temp = br.readLine()) != null) {
            buffer.append(temp);
            buffer.append("\n");
        }

        return buffer.toString();
    }

    /**
     * 识别图片_按图片文件路径
     *
     * @param username  用户名
     * @param password  密码
     * @param softid    软件ID
     * @param codetype  图片类型
     * @param len_min   最小位数
     * @param time_add  附加时间
     * @param str_debug 开发者自定义信息
     * @param filePath  图片文件路径
     * @return
     * @throws java.io.IOException
     */
    public static String postPic(String username, String password,
                                 String softid, String codetype, String len_min, String time_add, String str_debug,
                                 String filePath) {
        String result = "";
        String param = String
                .format(
                        "user=%s&pass=%s&softid=%s&codetype=%s&len_min=%s&time_add=%s&str_debug=%s",
                        username, password, softid, codetype, len_min, time_add, str_debug);
        try {
            File f = new File(filePath);
            if (null != f) {
                int size = (int) f.length();
                byte[] data = new byte[size];
                FileInputStream fis = new FileInputStream(f);
                fis.read(data, 0, size);
                if (null != fis) fis.close();

                if (data.length > 0)
                    result = RecognizeCode.httpPostImage("http://upload.chaojiying.net/Upload/Processing.php", param, data);
            }
        } catch (Exception e) {
            result = "未知问题";
        }


        return result;
    }

    /**
     * 识别图片_按图片二进制流
     *
     * @param username  用户名
     * @param password  密码
     * @param softid    软件ID
     * @param codetype  图片类型
     * @param len_min   最小位数
     * @param time_add  附加时间
     * @param str_debug 开发者自定义信息
     * @param byteArr   图片二进制数据流
     * @return
     * @throws java.io.IOException
     */
    public static String postPic(String username, String password,
                                 String softid, String codetype, String len_min, String time_add, String str_debug,
                                 byte[] byteArr) {
        String result = "";
        String param = String.format("user=%s&pass=%s&softid=%s&codetype=%s&len_min=%s&time_add=%s&str_debug=%s",
                username, password, softid, codetype, len_min, time_add, str_debug);
        try {
            result = RecognizeCode.httpPostImage("http://upload.chaojiying.net/Upload/Processing.php", param, byteArr);
        } catch (Exception e) {
            result = "未知问题";
        }


        return result;
    }

}